<template>
	<main-content>
		<view class="content-color">
			<u-form :model="formData" ref="formDataRef" :rules='rules' label-width='auto'
				:label-style="{color: 'rgba(153, 153, 153, 1)' }">
				<view :class="{isDisabled:formType=='view'}" class="p-b-90">
					<view class="p-16">
						<group-title>
						<template #icon>
							<view class="main-color">
								<u-icon name="title-icon" custom-prefix="custom-icon" />
							</view>
						</template>
						基本信息</group-title>
					</view>
					<view class="bg-white p-r-16 p-l-16">
						<u-form-item label="商户注册类型" prop="jSubject.subjectType"
							:required="rules['jSubject.subjectType']?.[0].required">
							<view class="flex flex-row justify-end w-100">
								<uni-data-checkbox v-model="jSubject.subjectType" :localdata="SUBJECT_TYPE_LAKALA" />
							</view>
						</u-form-item>
						<u-form-item label="协议" prop="jSubject.agreeMent"
							:required="rules['jSubject.agreeMent']?.[0].required">
							<view class="flex flex-row justify-end w-100">
								<fileUpload v-model="jSubject.agreeMent" ref="fileUploadRef" @upload="selectUpload"
									:maxCount="1" />
							</view>
						</u-form-item>
					</view>

					<view class="p-16">
						<group-title>
						<template #icon>
							<view class="main-color">
								<u-icon name="title-icon" custom-prefix="custom-icon" />
							</view>
						</template>
						执照信息-法人身份证信息</group-title>
					</view>

					<view class="bg-white p-r-16 p-l-16">
						<template v-for="(item, index) in jIdentitiesList" :key="`${item?.userType}` - `${index}`">
							<template v-if="item?.userType == 1">
								<u-form-item label="法人姓名" :prop="`jIdentitiesList.${index}.idDocName`"
									:required="rules[`jIdentitiesList.${index}.idDocName`]?.[0].required">
									<u-input input-align='right' v-model="item.idDocName" />
								</u-form-item>
								<u-form-item label="身份证号码" :prop="`jIdentitiesList.${index}.idDocNumber`"
									:required="rules[`jIdentitiesList.${index}.idDocNumber`]?.[0].required">
									<u-input input-align='right' v-model="item.idDocNumber" />
								</u-form-item>
								<u-form-item label="证件有效期开始时间" :prop="`jIdentitiesList.${index}.idDocPeriodBegin`"
									:required="rules[`jIdentitiesList.${index}.idDocPeriodBegin`]?.[0].required">
									<view class="flex flex-row justify-end w-100">
										<view style="width: fit-content;">
											<uni-datetime-picker return-type='string' type="date"
												v-model="item.idDocPeriodBegin" :border="false" :clearIcon='false'
												:end='item.idDocPeriodEnd' />
										</view>
									</view>
								</u-form-item>
								<u-form-item label="证件有效期结束时间" :prop="`jIdentitiesList.${index}.idDocPeriodEnd`"
									:required="rules[`jIdentitiesList.${index}.idDocPeriodEnd`]?.[0].required">
									<view class="flex flex-row justify-end w-100">
										<view style="width: fit-content;">
											<uni-datetime-picker return-type='string' type="date"
												v-model="item.idDocPeriodEnd" :border="false" :clearIcon='false'
												:start='item.idDocPeriodBegin' />
										</view>
									</view>
								</u-form-item>
								<u-form-item label="证件正面照片" :prop="`jIdentitiesList.${index}.idDocCopy`"
									:required="rules[`jIdentitiesList.${index}.idDocCopy`]?.[0].required">
									<view class="flex flex-row justify-end w-100">
										<fileUpload v-model="item.idDocCopy" @upload="selectUpload" :maxCount="1" />
									</view>
								</u-form-item>
								<u-form-item label="证件反面照片" :prop="`jIdentitiesList.${index}.idDocCopyBack`"
									:required="rules[`jIdentitiesList.${index}.idDocCopyBack`]?.[0].required">
									<view class="flex flex-row justify-end w-100">
										<fileUpload v-model="item.idDocCopyBack" @upload="selectUpload" :maxCount="1" />
									</view>
								</u-form-item>
							</template>
						</template>
					</view>

					<template v-if="jSubject.subjectType == 5">
						<view class="p-y-16">
							<group-title>
						<template #icon>
							<view class="main-color">
								<u-icon name="title-icon" custom-prefix="custom-icon" />
							</view>
						</template>
						执照信息-营业执照信息</group-title>
						</view>
						<view class="bg-white p-r-16 p-l-16">
							<u-form-item label="营业执照名称" prop="jSubject.businessLicenseName"
								:required="rules['jSubject.businessLicenseName']?.[0].required">
								<u-input input-align='right' v-model="jSubject.businessLicenseName" />
							</u-form-item>
							<u-form-item label="营业执照号码" prop="jSubject.businessLicenseNo"
								:required="rules['jSubject.businessLicenseNo']?.[0].required">
								<u-input input-align='right' v-model="jSubject.businessLicenseNo" />
							</u-form-item>
							<u-form-item label="证件有效期开始时间" :prop="`jSubject.businessLicenseDtStart`"
								:required="rules[`jSubject.businessLicenseDtStart`]?.[0].required">
								<view class="flex flex-row justify-end w-100">
									<view style="width: fit-content;">
										<uni-datetime-picker return-type='string' type="date"
											v-model="jSubject.businessLicenseDtStart" :border="false" :clearIcon='false'
											:end='jSubject.businessLicenseDtEnd' />
									</view>
								</view>
							</u-form-item>
							<u-form-item label="证件有效期结束时间" :prop="`jSubject.businessLicenseDtEnd`"
								:required="rules[`jSubject.businessLicenseDtEnd`]?.[0].required">
								<view class="flex flex-row justify-end w-100">
									<view style="width: fit-content;">
										<uni-datetime-picker return-type='string' type="date"
											v-model="jSubject.businessLicenseDtEnd" :border="false" :clearIcon='false'
											:start='jSubject.businessLicenseDtStart' />
									</view>
								</view>
							</u-form-item>
							<u-form-item label="营业执照图片" prop="jSubject.businessLicensePic"
								:required="rules['jSubject.businessLicensePic']?.[0].required">
								<view class="flex flex-row justify-end w-100">
									<fileUpload v-model="jSubject.businessLicensePic" ref="fileUploadRef"
										@upload="selectUpload" :maxCount="1" />
								</view>
							</u-form-item>
						</view>
					</template>

					<view class="p-y-16">
						<group-title>
						<template #icon>
							<view class="main-color">
								<u-icon name="title-icon" custom-prefix="custom-icon" />
							</view>
						</template>
						商户信息</group-title>
					</view>
					<view class="bg-white p-r-16 p-l-16">
						<u-form-item label="营业执照号码" prop="jSubject.merchantShortName"
							:required="rules['jSubject.merchantShortName']?.[0].required">
							<u-input input-align='right' v-model="jSubject.merchantShortName" />
						</u-form-item>
						<u-form-item label="商户类别" prop="jSubject.mccCodeTwo"
							:required="rules['jSubject.mccCodeTwo']?.[0].required">
							<my-select clearable input-align='right' v-model="jSubject.mccCodeTwo"
								:queryParams="headParams" :initParams="headInitParams" :api="businessApi.page"
								labelKey='categoryName' valueKey='categoryCode' @change='changeMccCodeOne' />
						</u-form-item>
						<u-form-item label="商户经营内容" prop="jSubject.businessContent"
							:required="rules['jSubject.businessContent']?.[0].required">
							<u-input input-align='right' v-model="jSubject.businessContent" />
						</u-form-item>
						<u-form-item label="商户经营名称" prop="jSubject.merName"
							:required="rules['jSubject.merName']?.[0].required">
							<u-input input-align='right' v-model="jSubject.merName" />
						</u-form-item>
						<u-form-item label="联系人姓名" prop="jSubject.name"
							:required="rules['jSubject.name']?.[0].required">
							<u-input input-align='right' v-model="jSubject.name" />
						</u-form-item>
						<u-form-item label="联系人手机号" prop="jSubject.phone"
							:required="rules['jSubject.phone']?.[0].required">
							<u-input input-align='right' v-model="jSubject.phone" />
						</u-form-item>
						<u-form-item label="商户邮箱" prop="jSubject.email"
							:required="rules['jSubject.email']?.[0].required">
							<u-input input-align='right' v-model="jSubject.email" />
						</u-form-item>
					</view>

					<view class="p-y-16">
						<group-title>
						<template #icon>
							<view class="main-color">
								<u-icon name="title-icon" custom-prefix="custom-icon" />
							</view>
						</template>
						商户信息</group-title>
					</view>
					<view class="bg-white p-r-16 p-l-16">
						<u-form-item label="结算人银行卡号" prop="jBankAccounts.accountNumber"
							:required="rules['jBankAccounts.accountNumber']?.[0].required">
							<u-input input-align='right' v-model="jBankAccounts.accountNumber" />
						</u-form-item>
						<u-form-item label="结算账户名称" prop="jBankAccounts.accountName"
							:required="rules['jBankAccounts.accountName']?.[0].required">
							<u-input input-align='right' v-model="jBankAccounts.accountName" />
						</u-form-item>
						<u-form-item label="结算信息省份" prop="jBankAccounts.settleProvinceName"
							:required="rules['jBankAccounts.settleProvinceName']?.[0].required">
							<my-select clearable input-align='right' v-model="jBankAccounts.settleProvinceName"
								@change="changeProvince" :api="bankApi.lakalaBankArea" queryParamKey='nameLike'
								labelKey='name' valueKey='name' />
						</u-form-item>
						<u-form-item label="结算信息城市" prop="jBankAccounts.settleCityName"
							:required="rules['jBankAccounts.settleCityName']?.[0].required">
							<my-select clearable input-align='right' v-model="jBankAccounts.settleCityName"
								:queryParams="{ parentCode: jBankAccounts.settleProvinceCode }" @change="changeCity"
								:api="bankApi.lakalaBankArea" queryParamKey='nameLike' labelKey='name'
								valueKey='name' />
						</u-form-item>
						<u-form-item label="开户行名称" prop="jBankAccounts.bankName"
							:required="rules['jBankAccounts.bankName']?.[0].required"
							v-if="jBankAccounts.settleProvinceCode">
							<my-select clearable input-align='right' v-model="jBankAccounts.bankName"
								:api="bankApi.lakalaBank" queryParamKey='bankName'
								:queryParams="{ areaCode: jBankAccounts.settleProvinceCode }" labelKey='branchBankName'
								valueKey='branchBankName' @change='changeBankName' />
						</u-form-item>
						<u-form-item label="开户行号" prop="jBankAccounts.bankBranchId"
							:required="rules['jBankAccounts.bankBranchId']?.[0].required">
							<u-input input-align='right' v-model="jBankAccounts.bankBranchId" disabled="true" />
							<!-- <my-select clearable input-align='right' v-model="jBankAccounts.bankBranchId"
								:api="bankApi.lakalaBank" queryParamKey='branchBankNo' labelKey='branchBankNo'
								valueKey='branchBankNo' /> -->
						</u-form-item>
						<u-form-item label="清算行号" prop="jBankAccounts.clearingBankCode"
							:required="rules['jBankAccounts.clearingBankCode']?.[0].required">
							<u-input input-align='right' v-model="jBankAccounts.clearingBankCode" disabled="true" />
							<!-- <my-select clearable input-align='right' v-model="jBankAccounts.clearingBankCode"
								:api="bankApi.lakalaBank" queryParamKey='clearNo' labelKey='clearNo'
								valueKey='clearNo' /> -->
						</u-form-item>
						<u-form-item label="结算方式" prop="jSubject.settlementType"
							:required="rules['jSubject.settlementType']?.[0].required">
							<my-select clearable input-align='right' v-model="jSubject.settlementType"
								:options="SETTLEMENT_TYPE_LAKALA" />
						</u-form-item>
						<u-form-item label="定时结算时间" prop="jSubject.regularSettlementTime"
							:required="rules['jSubject.regularSettlementTime']?.[0].required"
							v-if="jSubject.settlementType == 'REGULAR'">
							<view class="flex flex-row justify-end w-100">
								<picker mode="time" :value="jSubject.regularSettlementTime" @change="bindTimeChange"
									class="flex flex-row justify-end w-100">
									<view class="uni-input w-100">{{jSubject.regularSettlementTime || '请选择时间'}}</view>
								</picker>
							</view>
						</u-form-item>
						<u-form-item label="结算周期" prop="jSubject.settleType"
							:required="rules['jSubject.settleType']?.[0].required">
							<view class="flex flex-row justify-end w-100">
								<uni-data-checkbox v-model="jSubject.settleType" :localdata="SETTLE_TYPE_LAKALA" />
							</view>
						</u-form-item>
						<u-form-item label="银行卡正面照" prop="jSubject.bankCard"
							:required="rules['jSubject.bankCard']?.[0].required">
							<view class="flex flex-row justify-end w-100">
								<fileUpload v-model="jSubject.bankCard" ref="fileUploadRef" @upload="selectUpload"
									:maxCount="1" />
							</view>
						</u-form-item>
						<u-form-item label="开户许可证" prop="jSubject.openingPermit"
							:required="rules['jSubject.openingPermit']?.[0].required"
							v-if="jSubject.subjectType == '5'">
							<view class="flex flex-row justify-end w-100">
								<fileUpload v-model="jSubject.openingPermit" ref="fileUploadRef" @upload="selectUpload"
									:maxCount="1" />
							</view>
						</u-form-item>
					</view>

					<view class="p-y-16">
						<group-title>
						<template #icon>
							<view class="main-color">
								<u-icon name="title-icon" custom-prefix="custom-icon" />
							</view>
						</template>
						费率信息</group-title>
					</view>
					<view class="bg-white p-r-16 p-l-16">
						<u-form-item label="线上成本价">
							<u-input input-align='right' v-model="rateF.onlineRate" disabled placeholder='' />
						</u-form-item>
						<u-form-item label="线下成本价">
							<u-input input-align='right' v-model="rateF.offlineRate" disabled placeholder='' />
						</u-form-item>
						<u-form-item label="微信/支付宝费率" prop="jSubject.rate"
							:required="rules['jSubject.rate']?.[0].required">
							<u-input input-align='right' v-model="jSubject.rate" />
						</u-form-item>
					</view>

					<view class="p-y-16">
						<group-title>
						<template #icon>
							<view class="main-color">
								<u-icon name="title-icon" custom-prefix="custom-icon" />
							</view>
						</template>
						费率信息</group-title>
					</view>
					<view class="bg-white p-r-16 p-l-16">
						<u-form-item label="门头照" prop="jSubject.shopOutsideImg"
							:required="rules['jSubject.shopOutsideImg']?.[0].required">
							<view class="flex flex-row justify-end w-100">
								<fileUpload v-model="jSubject.shopOutsideImg" ref="fileUploadRef" @upload="selectUpload"
									:maxCount="1" />
							</view>
						</u-form-item>
						<u-form-item label="商铺内部照片" prop="jSubject.shopInsideImg"
							:required="rules['jSubject.shopInsideImg']?.[0].required">
							<view class="flex flex-row justify-end w-100">
								<fileUpload v-model="jSubject.shopInsideImg" ref="fileUploadRef" @upload="selectUpload"
									:maxCount="1" />
							</view>
						</u-form-item>
						<u-form-item label="收银台照" prop="jSubject.checkstandImg"
							:required="rules['jSubject.checkstandImg']?.[0].required">
							<view class="flex flex-row justify-end w-100">
								<fileUpload v-model="jSubject.checkstandImg" ref="fileUploadRef" @upload="selectUpload"
									:maxCount="1" />
							</view>
						</u-form-item>
					</view>
				</view>
			</u-form>
			<view class="formBtn"
				v-if="(userType == 2 && rowData.status == '0' && rowData.checkStatus == '-1')||formType=='add'">
				<view class="p-16 flex flex-row justify-between" v-if="formType=='view'">
					<view class="w-100">
						<u-button @click="updateForm">修改</u-button>
					</view>
				</view>
				<view class="p-16 flex flex-row justify-between" v-else>
					<view class="w-30">
						<u-button @click="getHistoryData">调取进件资料</u-button>
					</view>
					<view class="w-30">
						<u-button @click="handleSave">保存</u-button>
					</view>
					<view class="w-30">
						<u-button type="primary" @click="submit">提交</u-button>
					</view>
				</view>
			</view>
		</view>
	</main-content>
</template>
<script setup name='index'>
	import {
		reactive,
		ref,
		getCurrentInstance,
		computed,
		nextTick,
		toRefs,
		watch
	} from 'vue'
	import {
		onLoad,
		onShow,
		onReady
	} from '@dcloudio/uni-app'
	import {
		useCommonStore
	} from '@/stores/common.js'
	import {
		useUserStore
	} from '@/stores/user.js'
	import {
		SUBJECT_TYPE_LAKALA, //应用市场
		SETTLEMENT_TYPE_LAKALA, //结算方式
		SETTLE_TYPE_LAKALA, //结算类型
	} from '@/common/dict.js'
	import {
		debounce,
		selectDictLabel,
		parseTime,
		cloneDeep,
		parseQueryParams,
		modifyFields,
		strToArr
	} from '@/common/common.js'
	import {
		myUpload
	} from '@/pages-menus/common/myUpload.js'
	import {
		registApi
	} from '@/pages-menus/common/api/regist/index.js'
	import {
		businessApi
	} from '@/pages-menus/common/api/regist/business.js'
	import {
		bankApi
	} from '@/pages-menus/common/api/bank/index.js'
	import {
		agentPayconfigApi
	} from '@/pages-menus/common/api/agent/agent-payconfig.js'

	import fileUpload from '@/pages-menus/components/file-upload/index.vue'
	import {
		validatePhoneNot,
		isNum
	} from '@/common/validate'
	const userType = computed(() => {
		return useUserStore().userType
	})
	const commonStore = useCommonStore()
	const {
		proxy
	} = getCurrentInstance()

	const formType = ref('add')
	const rowData = ref({})

	const maiColor = computed(() => {
		return proxy.$System.maiColor.value
	})
	const formDataRef = ref(null)

	const validatorFn = (rule, value, callback) => {
		const judge = rule.judge ?? (() => {
			return true
		})
		const mes = rule.message || '不能为空'

		if (judge(value)) {
			callback(new Error(mes));
		} else {
			callback();
		}
	}

	const rules = computed(() => {
		let obj = {
			sceneTypeArr: [{
				required: false,
				validator: validatorFn,
				judge: (val) => {
					return !val || val.length === 0
				},
				message: '交易场景 不能为空!',
				trigger: ['blur', 'change']
			}], //交易场景
			'jSubject.account': [{
				required: true,
				message: '商户号/支付宝账号不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.name': [{
				required: true,
				message: '姓名不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.phone': [{
					required: true,
					message: '手机号码不能为空!',
					trigger: ['blur', 'change']
				},
				{
					validator: validatePhoneNot,
				},
			],
			'jSubject.email': [{
				required: true,
				message: '商户邮箱 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.businessLicenseName': [{
				required: true,
				message: '营业执照名称 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.subjectType': [{
				required: true,
				message: '主体类型 不能为空!'
			}],
			'jSubject.businessLicenseDtStart': [{
				required: true,
				message: '营业执照开始时间 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.businessLicenseDtEnd ': [{
				required: true,
				message: '营业执照结束时间 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.merchantShortName ': [{
				required: true,
				message: '商户注册名称 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.mccCodeOne': [{
				required: true,
				message: '经营类目 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.businessContent': [{
				required: true,
				message: '营业执照上的经营内容 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.merName': [{
				required: true,
				message: '商户经营名称 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.settleType': [{
				required: true,
				message: '结算类型 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.settlementType': [{
				required: true,
				message: '结算方式 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.regularSettlementTime': [{
				required: true,
				message: '定时结算时间 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.mccCodeTwo': [{
				required: true,
				message: '经营类目 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.rate': [{
				required: true,
				message: '费率 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.specialQualifications': [{
				required: false,
				validator: validatorFn,
				judge: (val) => {
					return jSubject.value.specialLicenseType == '0' && (!val || val.length === 0)
				},
				trigger: ['blur', 'change'],
			}],
			'jSubject.agreeMent': [{
				required: true,
				message: '协议照片 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.bankCard': [{
				required: true,
				message: '银行卡照片 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.openingPermit': [{
				required: true,
				message: '开店许可证照片 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.shopOutsideImg': [{
				required: true,
				message: '门头照 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.shopInsideImg': [{
				required: true,
				message: '店铺内照 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.checkstandImg': [{
				required: true,
				message: '收银台照 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.businessLicenseNo': [{
				required: true,
				message: '营业执照号码 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.businessLicenseMobile': [{
				required: true,
				message: '营业执照法人手机号 不能为空!',
				trigger: ['blur', 'change']
			}],
			'jSubject.businessLicensePic': [{
				required: false,
				validator: validatorFn,
				judge: (val) => {
					return jSubject.value.subjectType == '0' && (!val || val.length === 0)
				},
				trigger: ['blur', 'change'],
				message: '营业执照图片 不能为空!',
			}],

			'jBankAccounts.bankAccountType': [{
				required: true,
				message: '账户类型 不能为空!'
			}],
			'jBankAccounts.accountName': [{
				required: true,
				message: '开户名称 不能为空!',

			}],
			'jBankAccounts.accountBank': [{
				required: true,
				message: '开户银行 不能为空!',

			}],
			'jBankAccounts.bankAddressCode': [{
				required: false,
				message: '开户行地区 不能为空!',

			}],
			'jBankAccounts.bankBranchId': [{
				required: false,
				message: '开户银行银行号 不能为空!',

			}],
			'jBankAccounts.settleProvinceCode': [{
				required: false,
				validator: validatorFn,
				judge: (val) => {
					return jBankAccounts.value.needBankBranch && (!val || val.length === 0)
				},
				message: '结算信息省份 不能为空!',

			}],
			'jBankAccounts.settleCityCode': [{
				required: false,
				validator: validatorFn,
				judge: (val) => {
					return jBankAccounts.value.needBankBranch && (!val || val.length === 0)
				},
				message: '结算信息城市 不能为空!',

			}],
			'jBankAccounts.settleProvinceName': [{
				required: false,
				validator: validatorFn,
				judge: (val) => {
					return jBankAccounts.value.needBankBranch && (!val || val.length === 0)
				},
				message: '结算信息省份 不能为空!',

			}],
			'jBankAccounts.settleCityName': [{
				required: false,
				validator: validatorFn,
				judge: (val) => {
					return jBankAccounts.value.needBankBranch && (!val || val.length === 0)
				},
				message: '结算信息城市 不能为空!',

			}],
			'jBankAccounts.bankName': [{
				required: false,
				validator: validatorFn,
				judge: (val) => {
					return jBankAccounts.value.needBankBranch && (!val || val.length === 0)
				},
				message: '开户银行全称（含支行） 不能为空!',

			}],
			'jBankAccounts.accountNumber': [{
				required: true,
				message: '银行账号 不能为空!',

			}, {
				validator: isNum
			}],
		}

		if (jIdentitiesList.value && jIdentitiesList.value.length > 0) {
			jIdentitiesList.value.forEach((item, index) => {
				obj[`jIdentitiesList.${index}.idHolderType`] = [{
					required: true,
					message: '证件持有人类型 不能为空!',

				}]
				obj[`jIdentitiesList.${index}.idDocType`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return ((item.userType == '0' && item
								.idHolderType == 'SUPER') ||
							(item.userType == '1' && item
								.idHolderType == 'LEGAL') ||
							item.userType == '2') && (!val || val.length === 0)
					},
					message: '证件类型 不能为空!',
				}, ]
				obj[`jIdentitiesList.${index}.idDocName`] = [{
					required: true,
					message: '证件姓名 不能为空!',

				}]
				obj[`jIdentitiesList.${index}.idDocNumber`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return ((item.userType == '0' && item
								.idHolderType == 'SUPER') || item
							.userType != '0') && (!val || val.length === 0)
					},
					message: '证件号码 不能为空!',
				}]
				obj[`jIdentitiesList.${index}.idDocAddress`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return ((item.userType == '1' && jSubject
								.value.subjectType == '1') || item
							.userType != '1') && (!val || val.length === 0)
					},
					message: '证件居住地址 不能为空!',
				}, ]
				obj[`jIdentitiesList.${index}.idDocPeriodBegin`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return ((item.userType == '0' && item
								.idHolderType == 'SUPER') || item
							.userType != '0') && (!val || val.length === 0)
					},
					message: '证件有效期开始时间 不能为空!',
				}, ]
				obj[`jIdentitiesList.${index}.idDocPeriodEnd`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return ((item.userType == '0' && item
								.idHolderType == 'SUPER') || item
							.userType != '0') && (!val || val.length === 0)
					},
					message: '证件有效期结束时间 不能为空!',
				}, ]
				obj[`jIdentitiesList.${index}.idDocLongTermFlag`] = [{
					required: true,
					message: '证件是否长期有效 不能为空!',
				}]
				obj[`jIdentitiesList.${index}.userType`] = [{
					required: true,
					message: '用户类型 不能为空!',

				}]
				obj[`jIdentitiesList.${index}.owner`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return (item.userType == '1' && jSubject
							.value.subjectType == '1') && (!val || val.length === 0)
					},
					message: '是否受益人 不能为空!',

				}]
				obj[`jIdentitiesList.${index}.businessAuthorizationLetter`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return (item.idHolderType == 'SUPER') && (!val || val.length === 0)
					},
					message: '业务办理授权函 不能为空!',

				}]
				obj[`jIdentitiesList.${index}.authorizeLetterCopy`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return (item.idHolderType == 'SUPER') && (!val || val.length === 0)
					},
					message: '法定代表人说明函 不能为空!',

				}]
				obj[`jIdentitiesList.${index}.idDocCopy`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return ((item.userType == '0' && item
								.idHolderType == 'SUPER') || item
							.userType != '0') && (!val || val.length === 0)
					},
					message: '证件正面照片 不能为空!',
				}]
				obj[`jIdentitiesList.${index}.idDocCopyBack`] = [{
					required: false,
					validator: validatorFn,
					judge: (val) => {
						return ((item.userType == '0' && item
								.idHolderType == 'SUPER') || item
							.userType != '0') && (!val || val.length === 0)
					},
					message: '证件反面照片 不能为空!',
				}]
			})
		}
		return obj
	})

	// 图片字段
	const imgField = [
		'specialQualifications',
		'qualifications',
		'businessLicensePic',
		'financeLicensePics',
		'businessLicenseAuthPic',
		'indexUrl',
		'remarkUrl',
		'payUrl',
		'authorizationUrl',
		'productUrl',
		'idDocCopy',
		'idDocCopyBack',
		'authorizeLetterCopy',
		'businessAuthorizationLetter',
		'legalPersonCommitment',
		'legalPersonVideo',
		'businessAdditionPics',
		'agreeMent',
		'bankCard',
		'openingPermit',
		'shopOutsideImg',
		'shopInsideImg',
		'checkstandImg',
	]
	// 商户身份信息子表字段
	const jIdentitiesListChild = {
		idHolderType: undefined, //证件持有人类型（LEGAL：经营者/法人；SUPER：经办人）
		idDocType: undefined, //证件类型: 0: 中国大陆居民-身份证 1: 其他国家或地区居民-护照 2: 中国香港居民-来往内地通行证 3: 中国澳门居民-来往内地通行证 4: 中国台湾居民-来往大陆通行证 5: 外国人居留证 6: 港澳居民证 7: 台湾居民证
		idDocName: undefined, //证件姓名
		idDocNumber: undefined, //证件号码
		idDocAddress: undefined, //证件居住地址
		idDocPeriodBegin: undefined, //证件有效期开始时间
		idDocPeriodEnd: undefined, //证件有效期结束时间
		idDocLongTermFlag: undefined, //证件是否长期有效
		userType: undefined, //用户类型 0超级管理员 1经营者/法人 2最终受益人
		owner: undefined, //是否受益人 0否1是
		businessAuthorizationLetter: [], //业务办理授权函（仅当 contact_type= SUPER 时填写）
		authorizeLetterCopy: [], //法定代表人说明函
		idDocCopy: [], //证件正面照片
		idDocCopyBack: [], //证件反面照片
	}
	const initData = {
		mpdId: undefined, //商户进件关联编号
		jBankAccounts: {
			channelId: undefined, //通道id
			bankAccountType: undefined, //银行账户类型 0: 对公银行账户 1: 经营者个人银行卡
			accountName: undefined, //账户名称
			accountBank: undefined, //开户银行
			bankAddressCode: undefined, //银行地址编码
			bankBranchId: undefined, //银行支行ID
			bankName: undefined, //银行名称
			accountNumber: undefined, //银行账号
			needBankBranch: undefined, //是否需要支行
			clearingBankCode: undefined, //结算账户清算⾏号
			settleProvinceCode: undefined, //结算信息省份代码
			settleProvinceName: undefined, //结算信息省份名称
			settleCityCode: undefined, //结算信息城市代码
			settleCityName: undefined, //结算信息城市名称
			serviceType: undefined, //服务类型：1代收；2代付；3自动分账；4不分账
			auditStatus: undefined, //审核状态：1待审核；2审核中；3审核通过；4审核拒绝
			auditMsg: undefined, //审核原因
			settlementType: undefined, //结算方式：1银行卡；2支付宝账号
			outCode: undefined, //外部编号
			utime: undefined, //可选
		}, //结算银行账户表
		jSubject: {
			financeInstitution: undefined, //是否为金融机构 0否1是
			businessLicenseMobile: undefined, //营业执照法人手机号
			merchantShortName: undefined, //商户简称
			dateLimitation: undefined, //营业期限
			businessLicenseDtStart: undefined, //营业执照开始时间
			business_licenseDtEnd: undefined, //营业执照结束时间
			businessContent: undefined, //营业执照上的经营内容（拉卡拉20字以内）
			settleType: undefined, //结算类型：1 D0秒到；2 D1次日结算
			settlementType: undefined, //结算方式
			regularSettlementTime: undefined, //定时结算时间
			settlementId: undefined, //结算规则ID
			subjectType: undefined, //主体类型： 0: 营业执照上的主体类型一般为个体户、个体工商户、个体经营 1: 营业执照上的主体类型一般为有限公司、有限责任公司 2: 包括各级、各类政府机关，如机关党委、税务、民政、人社、工商、商务、市监等 3:包括国内各级、各类政府机构、事业单位等。 如：公安、党团、司法、交通、旅游、工商税务、市政、医疗、教育、学校等机构 4: 包括社会团体、民办非企业、基金会、基层群众性自治组织、农村集体经济组织等组织
			mccCode: undefined, //经营类目
			mccCodeOne: undefined, //经营类目
			mccCodeTwo: undefined, //经营类目
			activitiesAdditions: undefined, //活动附加说明 用,拼接
			qualificationType: undefined, //所属行业类型
			qualifications: [], //特殊资质说明 用,拼接
			signAndAuth: 1, //签约且授权标识，默认为false，只进行签约操作； 如果设置为true，则表示签约成功后，会自动进行应用授权操作。
			longTerm: 1, //营业执照是否长期有效 0否 1是
			activitiesId: undefined, //活动ID
			merchantId: undefined, //自定义商户编号
			rate: undefined, //服务费率（%），0.38~0.6 之间（小数点后两位，可取0.38%及0.6%）。 当签约且授权标识 sign_and_auth=true 时，该费率信息必填
			activitiesRate: undefined, //活动费率
			legalPersonVideo: undefined, //法人开户意愿视频 1、建议法人按如下话术录制“法人开户意愿视频”： 我是#公司全称#的法定代表人（或负责人），特此证明本公司申请的商户号为我司真实意愿开立且用于XX业务（或XX服务）。我司现有业务符合法律法规及腾讯的相关规定。 2、支持上传20M内的视频，格式可为avi、wmv、mpeg、mp4、mov、mkv、flv、f4v、m4v、rmvb； 3、请填写通过视频上传API预先上传视频生成好的MediaID 。
			id: undefined, //编号
			debitActivitiesRate: undefined, //借记卡活动费率
			creditActivitiesRate: undefined, //信用卡活动费率
			legalPersonCommitment: undefined, //法人开户承诺函1、请上传法定代表人或负责人亲笔签署的开户承诺函扫描件（下载模板）。亲笔签名承诺函内容清晰可见，不得有涂污，破损，字迹不清晰现象； 2、请填写通过图片上传API预先上传图片生成好的MediaID
			email: undefined, //邮箱
			specialLicenseType: undefined, //特殊资质类型
			certificateLetterCopy: undefined, //单位证明函照片
			businessLicenseAddress: undefined, //营业执照的注册地址，若该字段未填写，系统将会查询国家工商信息填入。需注意若工商信息查询不到，则会被审核驳回。
			servicePhone: undefined, //服务电话
			businessAdditionMsg: undefined, //补充说明
			businessLicenseName: undefined, //营业执照商户名称
			businessLicenseNo: undefined, //营业执照号码
			businessAdditionPics: undefined, //补充材料 1、最多可上传5张照片； 2、请填写通过图片上传API预先上传图片生成好的MediaID。
			phone: undefined, //手机号
			name: undefined, //姓名
			financeType: undefined, //金融机构类型 为金融机构时必传
			storeInfo: undefined, //销售场景
			account: undefined, //支付宝账号
			specialQualifications: [], //企业特殊资质图片
			agreeMent: [], //协议照片
			bankCard: [], //银行卡照片
			openingPermit: [], //开店许可证图片
			shopOutsideImg: [], //门头照
			shopInsideImg: [], //店铺内照
			checkstandImg: [], //收银台照
			businessLicensePic: [], //营业执照图片
			financeLicensePics: [], //金融机构许可证图片 用,拼接
			businessLicenseAuthPic: [], //营业执照授权函
		}, //商户经营信息表出参apiType: 1, //接口类型 0通用 1当面付
		jIdentitiesList: [], //商户身份信息
		sceneTypeArr: [], //场景类型
	}
	const formData = reactive(cloneDeep(initData))
	const {
		jBankAccounts,
		jSubject,
		jSceneList,
		jIdentitiesList
	} = toRefs(formData)

	//保存
	const handleSave = async () => {
		const param = {
			...cloneDeep(formData),
		}
		imgInit(param)
		if (formType.value != 'view') {
			try {
				let res = await registApi.save(param)
				uni.showToast({
					title: `保存成功！`,
					icon: 'success',
					duration: 2000
				});
				return res
			} catch (error) {
				console.error(error)
			}
		}
	}
	// 提交
	const submit = async () => {
		formDataRef.value.validate((valid) => {
			if (valid) {
				handleSave().then(() => {
					const param = {
						checkStatus: 0,
						id: rowData.value.id
					}
					registApi.submit(param).then(() => {
						uni.showToast({
							title: `提交成功！`,
							icon: 'success',
							duration: 2000
						});
						proxy.$System.goTo('/pages-menus/pages/regist/index', {}, {
							method: 'reLaunch'
						})
						resetForm()
					})
				})
			}
		})
	}

	//调用进件资料
	function getHistoryData() {
		SmartLoading.show()
		let p = {
			id: rowData.value.id,
			channelType: rowData.value.channelType
		}
		registApi
			.findIdByChannelType(p)
			.then((res) => {
				// jSubject/jSceneList
				if (proxy.$System.isEmpty(res?.data)) return
				let resData = res.data
				imgInit(resData)
				mergeArea(resData)
				Object.assign(formData, resData)
				initFormList()
			})
			.finally(() => {
				SmartLoading.hide()
			})
	}

	const resetForm = () => {
		// 重置表单的 UI 状态
		try {
			formDataRef.value.resetFields()
		} catch (error) {
			console.error(error)
		}
		// 重置表单数据
		Object.assign(formData, cloneDeep(initData))
	}

	const getForm = (data) => {
		let p = {
			mpdId: data.id,
			type: data.channelType
		}
		registApi.findId(p).then((res) => {
			if (res.code != 200) return
			let resData = res.data
			resData.mpdId = data.id
			imgInit(resData)
			mergeArea(resData)
			Object.assign(formData, resData)

			initFormList()
		}).catch((err) => {
			console.error(err)
			initFormList()
		})
	}
	const titleMap = {
		add: '新增拉卡拉资料',
		update: '修改拉卡拉资料',
		view: '查看拉卡拉资料',
	}

	const updateForm = () => {
		formType.value = 'update'
		// 动态设置标题
		uni.setNavigationBarTitle({
			title: titleMap[formType.value]
		})
	}

	// 选择商户===》
	const changeMch = (val) => {
		console.log('选择商户===>', val);
		// if (!val[0]) {
		// 	formData.value.merchantId = undefined
		// 	return
		// }
		// formData.value.merchantId = data[0].id
	}

	// 结算信息省市
	const changeProvince = (val) => {
		console.log(val)
		if (proxy.$System.isEmpty(val)) {
			jBankAccounts.value.settleProvinceName = ''
			jBankAccounts.value.settleProvinceCode = ''
			return
		}
		jBankAccounts.value.settleProvinceCode = val[0].code
	}
	const changeCity = (val) => {
		if (proxy.$System.isEmpty(val)) {
			jBankAccounts.value.settleCityName = ''
			jBankAccounts.value.settleCityCode = ''
			return
		}
		jBankAccounts.value.settleCityCode = val[0].code
	}
	// 选择时间
	const bindTimeChange = (val) => {
		// console.log('bindTimeChange===》', val);
		if (proxy.$System.isEmpty(val.detail.value)) return
		jSubject.value.regularSettlementTime = val.detail.value.replace(/\:/g, '')
		// console.log('jSubject.value.regularSettlementTime===》', jSubject.value.regularSettlementTime);
	}
	const oncancelregularSettlement = () => {
		jSubject.value.regularSettlementTime = ''
	}

	const limitUpload = {
		fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
		fileSize: 5,
	}
	const beforeUpload = (file, fileList, type) => {
		// 校检文件类型
		if (limitUpload.fileType.length) {
			const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
			const isTypeOk = limitUpload.fileType.includes(fileExt)
			if (!isTypeOk) {
				uni.showToast({
					title: `文件格式不正确, 请上传${limitUpload.fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`,
					icon: 'error',
					duration: 2000
				});
				return false
			}
		}

		// 校检文件大小
		if (limitUpload.fileSize) {
			const isLt = file.size / 1024 / 1024 < limitUpload.fileSize
			if (!isLt) {
				uni.showToast({
					title: `上传文件大小不能超过 ${limitUpload.fileSize} MB!`,
					icon: 'error',
					duration: 2000
				});
				return false
			}
		}

		return true
	}

	// 上传文件自定义的方法
	const uploadFunc = async (file, fieldName) => {
		// 确保获取到文件对象
		const fileObj = file
		if (!fileObj) {
			return
		}
		const response = await myUpload(file)
		console.log('response==>', response)

		// let arr = getObjValue(formData, fieldName).map((item) => {
		// 	if (item.uid === fileObj.uid) {
		// 		uni.showToast({
		// 			title: `${fileObj.name} 上传成功`,
		// 			icon: 'success',
		// 			duration: 2000
		// 		});
		// 		return response
		// 	}
		// 	return item
		// })
		// setObjValue(formData, fieldName, arr)
	}
	const fileUploadRef = ref(null)
	const selectUpload = async (e) => {
		console.log('选择文件：', e)
		if (e.length > 0) {
			e.forEach(async fileItem => {
				if (beforeUpload(fileItem)) {
					let res = await uploadFunc(fileItem)
				} else {
					console.log('选择文件错误：', fileItem)
					fileItem.onError()
				}
			})
		}

	}

	let areaFieldArr = ['shopProvinceCode', 'shopCityCode', 'shopDistrictCode']
	// 地址拆分
	const changeArea = (val, data) => {
		if (Array.isArray(val) && val.length > 0) {
			val.forEach((item, index) => {
				data[areaFieldArr[index]] = item
			})
		} else {
			areaFieldArr.forEach(item => {
				data[item] = ''
			})
		}
	}
	// 地址合并
	function mergeArea(data) {
		data.jSceneList.forEach((item) => {
			if (item.sceneType == '0') {
				for (let i = 0; i <= areaFieldArr.length; i++) {
					if (!item[areaFieldArr[i]]) {
						item.shopAddress1 = item[areaFieldArr[i - 1]]
					}
				}
			}
		})
	}
	// 图片初始化
	function imgInit(resData) {
		modifyFields(resData, imgField, (value, key) => {
			let val
			if (proxy.$System.isEmpty(value)) return
			if (typeof value === 'string') {
				val = strToArr(value).map((item, index) => {
					return {
						uid: `db-file-${index}`,
						name: `${key}${index > 0 ? '_' + index : ''}`,
						status: 'done',
						extname: 'text',
						url: item,
					}
				})
			}
			if (Array.isArray(value)) {
				val = value.map((e) => {
					let url = ''
					if (e?.res?.url || e?.res?.data?.url) {
						url = e.res.url || e.res.data.url
					} else {
						url = e.url
					}
					return url
				}).toString()
			}
			return val
		})
	}

	/* 经营类目 */
	// 主体类型
	const headParams = computed(() => {
		return {
			channelType: 5,
		}
	})
	const headInitParams = computed(() => {
		return {
			categoryCode: jSubject.value.mccCodeOne,
		}
	})
	//  切换商户类别
	const changeMccCodeOne = (val) => {
		if (proxy.$System.isEmpty(val)) {
			jSubject.value.mccCodeOne = ''
			return
		}
		jSubject.value.mccCodeOne = oval[0].mccCode
	}

	// 切换开户行
	const changeBankName = (val) => {
		if (proxy.$System.isEmpty(val)) {
			jBankAccounts.value.bankBranchId = ''
			jBankAccounts.value.clearingBankCode = ''
			return
		}
		jBankAccounts.value.bankBranchId = val[0].branchBankNo
		jBankAccounts.value.clearingBankCode = val[0].clearNo
	}

	/* 数组表单初始化 */
	function initFormList() {
		// 必填人员处理
		formData.mpdId = formData?.mpdId ?? rowData.value?.id
		// 确保 jIdentitiesList 存在且是数组
		if (!Array.isArray(formData.jIdentitiesList)) {
			formData.jIdentitiesList = []
		}
		const requiredUserTypes = [1]
		// 一次性检查所需 userType 是否都存在
		const existingTypes = new Set(formData.jIdentitiesList.map((item) => item.userType))
		requiredUserTypes.forEach((userType) => {
			if (!existingTypes.has(userType)) {
				formData.jIdentitiesList.push({
					...cloneDeep(jIdentitiesListChild),
					userType
				})
			}
		})
	}

	// 获取成本价、代理费率
	const rateF = ref({
		onlineRate: undefined,
		offlineRate: undefined,
	})
	const getARate = async () => {
		const {
			productId,
			agentId,
			channelId
		} = rowData.value
		let params = {
			productId,
			agentId,
			channelId
		}

		const res = await agentPayconfigApi.getRate(params)
		if (res.code === 200) {
			rateF.value = res.data
		}
		console.log('111111=>>>>', rateF.value)
	}

	watch([() => rowData.value, () => formType.value], () => {
		// formData.apiType = rowData.value.apiType
		getARate()
		if (rowData.value?.apiType) {
			formData.apiType = rowData.value.apiType
		}
		if (rowData.value?.id) {
			formData.mpdId = rowData.value?.id
		}
		if ((formType.value == 'update' || formType.value == 'view')) {
			getForm(cloneDeep(rowData.value))
		}
		if (formType.value == 'add') {
			initFormList()
		}
	}, {
		deep: true,
		immediate: true
	})
	watch(() => rules.value, () => {
		nextTick(() => {
			formDataRef.value?.setRules(rules.value);
		})
	}, {
		deep: true,
		immediate: true
	})

	onLoad(async (opt) => {
		let options = parseQueryParams(opt)
		formType.value = options.formType ?? 'add'
		if (!proxy.$System.isEmpty(options.rowData)) {
			rowData.value = options.rowData
		}
		// 动态设置标题
		uni.setNavigationBarTitle({
			title: titleMap[formType.value]
		})
	})
	onReady(() => {
		nextTick(() => {
			formDataRef.value?.setRules(rules.value);
		})
		// paging.value.reload()
	})
</script>
<style lang='scss' scoped>
	.view-group {
		background-color: #fff;
	}

	.isDisabled {
		position: relative;
	}

	.isDisabled:before {
		position: absolute;
		content: '';
		display: block;
		width: 100%;
		height: 100%;
		background-color: rgba(25, 25, 25, .05);
		z-index: 9;
	}

	.formBtn {
		position: fixed;
		bottom: 0;
		width: 100%;
		z-index: 999;
		background-color: #fff;
		box-shadow: 0 -3px 6px #e1e1e1;
	}

	.operate-box {
		position: fixed;
		z-index: 99;
		bottom: 50rpx;
	}

	.tar {
		:deep(.u-input) {
			text-align: right !important;
		}
	}
</style>